package com.ibangnuo.manage.config.shiro;


import com.ibangnuo.framework.domain.Menu;
import com.ibangnuo.framework.domain.Role;
import com.ibangnuo.framework.domain.User;
import com.ibangnuo.framework.domain.ext.RoleExt;
import com.ibangnuo.framework.domain.ext.UserExt;
import com.ibangnuo.manage.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


/**
 * @Author: wwy
 * @Date: 2019-11-07 10:15
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.getPrimaryPrincipal();
        User user = userService.findByUsernameNew(username);
        //记录权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //查询权限
        UserExt byRoleAndPermission = userService.findByRoleAndPermission(user.getId());
        List<RoleExt> roles = byRoleAndPermission.getRoles();
        for (RoleExt role : roles) {
            for (Menu menu : role.getMenus()) {
                info.addStringPermission(role.getRoleName()+":"+menu.getCode());
            }
        }
        return info;
    }

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        User user = userService.findByUsernameNew(usernamePasswordToken.getUsername());
        if(user==null){
            return null;
        }
        ByteSource salt = ByteSource.Util.bytes("wang");
        //第一个参数调用login方法返回的数据，第二个数据中的密码，第三个参数用户名
        return new SimpleAuthenticationInfo(user,user.getPassword(),salt,"");
    }

}
